package cn.lr.org.service.impl;

import cn.lr.basic.service.impl.BaseServiceImpl;
import cn.lr.basic.util.MD5Utils;
import cn.lr.basic.util.StrUtils;
import cn.lr.org.domain.Employee;
import cn.lr.org.mapper.EmployeeMapper;
import cn.lr.org.service.IEmployeeService;
import cn.lr.user.domain.Logininfo;
import cn.lr.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
   private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void save(Employee employee) {
        initEmployee(employee);
        Logininfo logininfo = employee2logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
        initRelationTable(employee);
    }

    private void initRelationTable(Employee employee) {
        employeeMapper.removeRole(employee.getId());
        employeeMapper.saveRole(employee.getId(),employee.getRoles());
    }

    private Logininfo employee2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0); // 手动设置
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        employeeMapper.update(employee);
    }

    @Override
    public Employee loadByLoginInfoId(Long id) {

        return employeeMapper.loadByLoginInfoId(id);
    }
}
